//
//  NSObject+Block.swift
//  NetWork
//
//  Created by Delin Meng 孟德林 on 2018/9/21.
//  Copyright © 2018年 Delin Meng 孟德林. All rights reserved.
//

import UIKit

extension NSObject {

    private struct AssociatedKeys {
        static var overviewKey = "NSObject.ActionUIControlBlock"
    }

    typealias ActionUIControlBlock = (Any) -> ()
    typealias ActionUIGestureRecognizerBlock = (Any) -> ()


    /// 拦截UIControls响应事件
    func onlyHangdleUIControlEvent(controlEvent:UIControlEvents,action:@escaping ActionUIControlBlock) {
        objc_setAssociatedObject(self, &AssociatedKeys.overviewKey, action, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        (self as? UIControl)?.addTarget(self, action: #selector(callUIControlActionBlock), for: controlEvent)
    }

    @objc private func callUIControlActionBlock(sender:Any) {
        if  let block = objc_getAssociatedObject(self, &AssociatedKeys.overviewKey) as? ActionUIControlBlock {
            block(sender)
        }
    }

    /// 拦截 UIGestureRecognizer 响应事件
    func onlyHangdleUIGestureRecognizer(action:@escaping ActionUIGestureRecognizerBlock) {
        objc_setAssociatedObject(self, &AssociatedKeys.overviewKey, action, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        (self as? UIGestureRecognizer)?.addTarget(self, action: #selector(callUIGestureRecognizerActionBlock))
    }


    @objc private func callUIGestureRecognizerActionBlock(recognizer:Any) {
        if let block = objc_getAssociatedObject(self, &AssociatedKeys.overviewKey) as? ActionUIGestureRecognizerBlock {
            block(recognizer)
        }
    }



}


